package org.sxdata.jingwei.util.CommonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;

/**
 * @description https是对链接加了安全证书SSL的,推荐请求使用此类
 * @author lidongyang
 * @date 2018/06/12
 * @version 1.0
 * @since 1.0
 */
public class HttpsUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);


    public static String httpsPostRequest(String url, Map<String, Object> header, String data) {
        return sendPostUrl(url, header, data);
    }

    public static String httpsPostRequest(String url, Map<String, Object> header, Map<String, String> params) throws RuntimeException {
        String param = "";
        int i = 0;
        int c = params.size();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {

                if (i != c - 1) {
                    param += entry.getKey() + "=" + entry.getValue() + "&";
                } else {
                    param += entry.getKey() + "=" + entry.getValue();
                }
                i++;
            }
        }
        return httpsRequestWrapper("POST", url, header, param);
    }

    public static String httpsGetRequest(String url) {
        return httpsRequestWrapper("GET", url, null, null);

    }

    public static String httpsGetRequest(String url, Map<String, Object> header) {

        return httpsRequestWrapper("GET", url, header, null);

    }

    public static String httpsGetRequest(String url, Map<String, Object> header, String data) {
        return httpsRequestWrapper("GET", url, header, data);
    }

    public static String httpsPutRequest(String url, Map<String, Object> header, String params) {
        return httpsRequestWrapper("PUT", url, header, params);
    }

    public static String httpsRequestWrapper(String method, String url, Map<String, Object> header, String params) throws RuntimeException {
        long startTime, endTime, costTime;
        startTime = System.currentTimeMillis();
        try {
            return httpsRequest(method, url, header, params);
        } finally {
            endTime = System.currentTimeMillis();
            costTime = endTime - startTime;
            logger.info("call url:{},cost:{}ms", url, costTime);
        }
    }

    /**
     * POST请求，字符串形式数据
     *
     * @param url    请求地址
     * @param header 请求头
     * @param param  请求数据
     */
    private static String sendPostUrl(String url, Map<String, Object> header, String param) {
        return httpsRequestWrapper("POST", url, header, param);
    }

    /**
     * POST请求，Map形式数据
     *
     * @param url    请求地址
     * @param header 请求头
     * @param param  请求数据
     */
    private static String sendPost(String url, Map<String, Object> header, Map<String, String> param) {
        return httpsPostRequest(url, header, param);

    }

    /*static{
	    //创建SSLContext
	    SSLContext sslContext = null;
	    try {
		    sslContext = SSLContext.getInstance("SSL");
		    TrustManager[] tm = {new ImTrustManager()};
		    KeyManager[] km= {new ImKeyManager()};
		    sslContext.init(km, tm, new java.security.SecureRandom());
		    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
	    } catch (NoSuchAlgorithmException e) {
		    e.printStackTrace();
	    }catch (KeyManagementException e) {
		    e.printStackTrace();
	    }
    }*/

    /**
     * 处理https GET/POST请求
     * @param requestMethod
     * @param requestUrl
     * @param header
     * @param outputStr
     * @return
     */
    public static String httpsRequest(String requestMethod, String requestUrl, Map<String, Object> header, String outputStr) {
        StringBuffer buffer = new StringBuffer();
	    InputStream is = null;
	    InputStreamReader isr = null;
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(true);
            conn.setRequestMethod(requestMethod);
//	        conn.setHostnameVerifier(new ImHostnameVerifier());

            if (header != null && !header.isEmpty()) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), (String) entry.getValue());
                }
            }

            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
	        is = conn.getInputStream();
	        isr = new InputStreamReader(is, "utf-8");
	        BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
	        CloseableUtil.close(is);
	        CloseableUtil.close(isr);
        }
        return buffer.toString();
    }
}
